import sensor, image, time
from machine import UART
from pyb import UART
import json
redblack_threshold   =(10, 63, 17, 65, 9, 50) #胶带
red_threshold =(11, 100, 16, 127, 1, 68)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_windowing(100,40,140,140)
sensor.set_vflip(True)##上下
#sensor.set_hmirror(True)##左右
sensor.skip_frames(10)
clock = time.clock()
sensor.set_auto_whitebal(False)#禁用白平衡
#sensor.set_auto_gain(False)#关闭自动增益
t=0
p=0
d = {}
i=0
mode=0
rx_buff=[]
state = 0
f=0
uart = UART(3, 115200, timeout_char=1000)
#串口接收函数
def Receive_Prepare(da):
    global state
    if state==0:
        if da == 0x0d:#帧头
            state = 1
        else:
            state = 0
            rx_buff.clear()
    elif state==1:
        rx_buff.append(da)
        mode=da
    else:
        state = 0
        rx_buff.clear()

while(True):
    img = sensor.snapshot()
    red_blobs = img.find_blobs([red_threshold])
    redblack_blobs=img.find_blobs([redblack_threshold])

    if(uart.any()>0):
       f=uart.readchar()
       Receive_Prepare(f)
       p=mode
       mode=f

    if mode==0:
        sensor.set_auto_exposure(False,10000)#设置曝光度

        if red_blobs:
            for a in red_blobs:
                img.draw_cross(a[5], a[6])
                print(a[5],a[6],mode)
                data = bytearray([0xb3,0xb3,0,0,0,0,0,0,0,0,a[5],a[6],0x0d,0x0a])
                uart.write(data)
    if p<mode:
        t=0
    if mode>=1:

        if t==0:
            sensor.set_auto_exposure(False,94000)#设置曝光度
        rects=img.find_rects(threshold = 10000)
        if rects:
            t=1
            for b in rects:
                img.draw_rectangle(b.rect())
                i=0
                for p in b.corners():
                    d[i]=p[0]
                    d[i+1]=p[1]
                    i+=2
                print(d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],mode)
                data = bytearray([0xb3,0xb3,d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],70, 70,0x0d,0x0a])
                uart.write(data)
        sensor.set_auto_exposure(False,120000)#设置曝光度
        if redblack_blobs or red_blobs:
            for a in redblack_blobs or red_blobs:
                img.draw_cross(a[5], a[6])
                data = bytearray([0xb3,0xb3,0,0,0,0,0,0,0,0,a[5], a[6],0x0d,0x0a])
                uart.write(data)
